
import React, { useState, useEffect } from 'react';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Plus, Trash2, Calculator, Shield, CheckCircle, Leaf, FileText, AlertTriangle } from 'lucide-react';
import { ConstructionMethodTemplate, SafetyRiskPoint } from '@/api/entities';
import { Badge } from '@/components/ui/badge';

export default function SchemeDetailStep({ data, onUpdate }) {
  const [riskData, setRiskData] = useState({}); // { stepIndex: { level, value, measures } }

  useEffect(() => {
    const evaluateRisks = async () => {
      // Ensure we have necessary data to proceed
      if (!data.constructionMethod || !data.constructionSteps || data.constructionSteps.length === 0) {
        setRiskData({}); // Clear risk data if dependencies are not met
        return;
      }
      
      try {
        // Fetch templates and all safety risk points
        const templates = await ConstructionMethodTemplate.filter({ methodName: data.constructionMethod });
        const allRisks = await SafetyRiskPoint.list();
        
        if (!templates || templates.length === 0 || !allRisks) {
            setRiskData({});
            return;
        }

        const template = templates[0]; // Assuming one template per methodName
        const newRiskData = {};
        // Use a Set to collect unique safety measures, including existing ones
        let autoFilledSafetyMeasures = new Set(data.safetyMeasures || []);

        data.constructionSteps.forEach((step, index) => {
            // Find the corresponding step in the template
            const templateStep = template.constructionSteps.find(ts => ts.stepName === step.stepName);
            
            if (templateStep && templateStep.associatedRiskCodes && templateStep.associatedRiskCodes.length > 0) {
                // Filter risks based on associated risk codes from the template step
                const stepRisks = allRisks.filter(r => templateStep.associatedRiskCodes.includes(r.riskCode));
                
                if (stepRisks.length > 0) {
                    // Find the maximum base risk value among identified risks for the step
                    const maxRiskValue = Math.max(...stepRisks.map(r => r.base_risk_value));
                    
                    let riskLevel = 'low'; // Default to low
                    if (maxRiskValue >= 15) riskLevel = 'critical'; // Higher value indicates critical risk
                    else if (maxRiskValue >= 10) riskLevel = 'high';
                    else if (maxRiskValue >= 5) riskLevel = 'medium';

                    // Collect unique control measures for this step
                    const measures = [...new Set(stepRisks.flatMap(r => r.controlMeasures || []))];
                    
                    // Add these measures to the overall auto-filled safety measures
                    measures.forEach(m => autoFilledSafetyMeasures.add(m));

                    newRiskData[index] = {
                        level: riskLevel,
                        value: maxRiskValue,
                        measures: measures,
                    };
                }
            }
        });
        
        setRiskData(newRiskData);
        // Automatically update the main safety measures list in the parent component
        onUpdate({ safetyMeasures: Array.from(autoFilledSafetyMeasures) });

      } catch (error) {
        console.error("风险评估失败:", error);
        setRiskData({}); // Clear risk data on error
      }
    };

    evaluateRisks();
  }, [data.constructionMethod, data.constructionSteps, data.safetyMeasures, onUpdate]);


  const handleChange = (field, value) => {
    onUpdate({ [field]: value });
  };

  const handleArrayAdd = (field, newItem) => {
    const currentArray = data[field] || [];
    onUpdate({ [field]: [...currentArray, newItem] });
  };

  const handleArrayRemove = (field, index) => {
    const currentArray = data[field] || [];
    onUpdate({ [field]: currentArray.filter((_, i) => i !== index) });
  };

  const handleArrayChange = (field, index, value) => {
    const currentArray = [...(data[field] || [])];
    currentArray[index] = value;
    onUpdate({ [field]: currentArray });
  };

  const updateStep = (index, updatedFields) => {
    const currentSteps = [...(data.constructionSteps || [])];
    if (currentSteps[index]) {
      currentSteps[index] = { ...currentSteps[index], ...updatedFields };
      onUpdate({ constructionSteps: currentSteps });
    }
  };

  // 封网长度计算
  const calculateNettingLength = () => {
    const Bw = parseFloat(data.crossedObjectWidth) || 0; // 被跨越物宽度
    const B = parseFloat(data.nettingWidth) || 0; // 封网宽度
    const alpha = parseFloat(data.crossingAngle) || 90; // 交叉角度
    const Lb = parseFloat(data.windDeflectionDepth) || 0; // 延伸长度

    if (Bw > 0 && B > 0 && alpha > 0) {
      const alphaRad = alpha * (Math.PI / 180);
      const La = Bw / Math.sin(alphaRad) + B / Math.tan(alphaRad) + 2 * Lb;
      return La.toFixed(2);
    }
    return null;
  };
  
  const riskLevelColors = {
    low: "bg-green-100 text-green-800 border-green-200",
    medium: "bg-yellow-100 text-yellow-800 border-yellow-200",
    high: "bg-orange-100 text-orange-800 border-orange-200",
    critical: "bg-red-100 text-red-800 border-red-200",
  };


  return (
    <div className="space-y-6">
      <div className="flex items-center gap-3 mb-6">
        <div className="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center">
          <FileText className="w-6 h-6 text-purple-600" />
        </div>
        <div>
          <h2 className="text-xl font-bold text-gray-900">方案详细内容</h2>
          <p className="text-gray-600">完善施工方案的详细信息</p>
        </div>
      </div>
      
      {/* 施工步骤与风险控制 - New Section */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <CheckCircle className="w-5 h-5 text-green-600" />
            施工步骤与风险控制
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
           {!data.constructionMethod || !data.constructionSteps || data.constructionSteps.length === 0 ? (
                <p className="text-sm text-gray-500">请在上一阶段选择施工方法并定义施工步骤以进行风险评估。</p>
            ) : (
                data.constructionSteps?.map((step, index) => (
                    <div key={index} className="p-4 border rounded-lg bg-gray-50/50">
                        <h4 className="font-semibold mb-2">步骤 {index + 1}: {step.stepName}</h4>
                        <p className="text-sm text-gray-600 mb-3">{step.description}</p>
                        
                        <div className="grid grid-cols-2 gap-4 mb-3">
                            <div>
                                <Label htmlFor={`step-duration-${index}`}>工期（天）</Label>
                                <Input
                                    id={`step-duration-${index}`}
                                    type="number"
                                    min="0.1"
                                    step="0.1"
                                    value={step.duration_days || ''}
                                    onChange={(e) => updateStep(index, { duration_days: parseFloat(e.target.value) || 0 })}
                                    placeholder="输入工期天数"
                                />
                            </div>
                        </div>

                        {riskData[index] ? (
                            <div className="p-3 bg-yellow-50 border-l-4 border-yellow-400 rounded">
                                <div className="flex items-center gap-2 mb-2">
                                    <AlertTriangle className="w-5 h-5 text-yellow-600" />
                                    <h5 className="font-semibold text-yellow-800">风险评估结果</h5>
                                    <Badge className={riskLevelColors[riskData[index].level]}>
                                        风险等级: {riskData[index].level.toUpperCase()} (值: {riskData[index].value})
                                    </Badge>
                                </div>
                                <ul className="list-disc list-inside text-xs text-yellow-700 space-y-1">
                                    {riskData[index].measures.map((measure, m_index) => (
                                        <li key={m_index}>{measure}</li>
                                    ))}
                                </ul>
                            </div>
                        ) : (
                            <p className="text-sm text-gray-500 italic">此步骤暂无匹配风险数据或未进行评估。</p>
                        )}
                    </div>
                ))
            )}
        </CardContent>
      </Card>


      <Tabs defaultValue="safety" className="w-full">
        <TabsList className="grid w-full grid-cols-4">
          <TabsTrigger value="safety">安全措施</TabsTrigger> {/* Moved to first position */}
          <TabsTrigger value="calculations">技术计算</TabsTrigger>
          <TabsTrigger value="quality">质量措施</TabsTrigger>
          <TabsTrigger value="environmental">环保措施</TabsTrigger>
        </TabsList>

        {/* 技术计算 */}
        <TabsContent value="calculations" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Calculator className="w-5 h-5 text-blue-600" />
                封网参数计算
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="crossedObjectWidth">被跨越物宽度 (m)</Label>
                  <Input
                    id="crossedObjectWidth"
                    type="number"
                    step="0.01"
                    value={data.crossedObjectWidth || ''}
                    onChange={(e) => handleChange('crossedObjectWidth', e.target.value)}
                    placeholder="例如: 24.5"
                  />
                </div>
                <div>
                  <Label htmlFor="crossingAngle">交叉角度 (°)</Label>
                  <Input
                    id="crossingAngle"
                    type="number"
                    step="0.1"
                    value={data.crossingAngle || ''}
                    onChange={(e) => handleChange('crossingAngle', e.target.value)}
                    placeholder="例如: 90"
                  />
                </div>
                <div>
                  <Label htmlFor="nettingWidth">封网宽度 (m)</Label>
                  <Input
                    id="nettingWidth"
                    type="number"
                    step="0.01"
                    value={data.nettingWidth || ''}
                    onChange={(e) => handleChange('nettingWidth', e.target.value)}
                    placeholder="例如: 30"
                  />
                </div>
                <div>
                  <Label htmlFor="windDeflectionDepth">延伸保护长度 (m)</Label>
                  <Input
                    id="windDeflectionDepth"
                    type="number"
                    step="0.01"
                    value={data.windDeflectionDepth || ''}
                    onChange={(e) => handleChange('windDeflectionDepth', e.target.value)}
                    placeholder="例如: 10"
                  />
                </div>
              </div>
              
              <div className="p-4 bg-green-50 rounded-lg border border-green-200">
                <Label className="font-semibold text-green-800">计算封网长度</Label>
                <div className="text-2xl font-bold text-green-700 mt-1">
                  {calculateNettingLength() ? `${calculateNettingLength()} m` : '请完善参数以计算'}
                </div>
                <p className="text-sm text-green-600 mt-1">
                  计算公式: La = Bw/sin(α) + B/tan(α) + 2*Lb
                </p>
              </div>
            </CardContent>
          </Card>

          {/* 张力校核 */}
          <Card>
            <CardHeader>
              <CardTitle>张力校核</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                  <Label htmlFor="conductorType">导线类型</Label>
                  <Input
                    id="conductorType"
                    value={data.conductorType || ''}
                    onChange={(e) => handleChange('conductorType', e.target.value)}
                    placeholder="例如: LGJ-300/40"
                  />
                </div>
                <div>
                  <Label htmlFor="spanLength_for_tension">校核档距 (m)</Label>
                  <Input
                    id="spanLength_for_tension"
                    type="number"
                    value={data.spanLength_for_tension || data.spanLength || ''}
                    onChange={(e) => handleChange('spanLength_for_tension', e.target.value)}
                    placeholder="例如: 350"
                  />
                </div>
                <div>
                  <Label htmlFor="designTension">设计张力 (kN)</Label>
                  <Input
                    id="designTension"
                    type="number"
                    step="0.01"
                    value={data.designTension || ''}
                    onChange={(e) => handleChange('designTension', e.target.value)}
                    placeholder="例如: 25.5"
                  />
                </div>
              </div>
            </CardContent>
          </Card>

          {/* 施工平面布置 */}
          <div>
            <Label htmlFor="siteLayoutPlan">施工平面布置</Label>
            <Textarea
              id="siteLayoutPlan"
              value={data.siteLayoutPlan || ''}
              onChange={(e) => handleChange('siteLayoutPlan', e.target.value)}
              placeholder="描述施工现场的总体布局，包括材料堆放、设备停放、临时设施等..."
              rows={4}
            />
          </div>
        </TabsContent>

        {/* 安全措施 */}
        <TabsContent value="safety" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Shield className="w-5 h-5 text-red-600" />
                安全保障措施
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div>
                <div className="flex justify-between items-center mb-2">
                  <Label>安全措施清单 <span className="text-gray-500 text-xs">(部分措施已根据风险自动带入)</span></Label>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => handleArrayAdd('safetyMeasures', '')}
                  >
                    <Plus className="w-4 h-4 mr-1" />
                    手动添加
                  </Button>
                </div>
                <div className="space-y-2">
                  {(data.safetyMeasures || []).map((measure, index) => (
                    <div key={index} className="flex gap-2">
                      <Textarea
                        value={measure}
                        onChange={(e) => handleArrayChange('safetyMeasures', index, e.target.value)}
                        placeholder="输入安全措施..."
                        rows={2}
                        className="flex-1"
                      />
                      <Button
                        variant="ghost"
                        size="icon"
                        onClick={() => handleArrayRemove('safetyMeasures', index)}
                      >
                        <Trash2 className="w-4 h-4 text-red-500" />
                      </Button>
                    </div>
                  ))}
                </div>
              </div>

              <div>
                <Label htmlFor="weatherRequirements">天气安全要求</Label>
                <Textarea
                  id="weatherRequirements"
                  value={data.weatherRequirements || ''}
                  onChange={(e) => handleChange('weatherRequirements', e.target.value)}
                  placeholder="描述施工对天气条件的安全要求..."
                  rows={3}
                />
              </div>

              <div>
                <Label htmlFor="emergencyPlan">应急预案</Label>
                <Textarea
                  id="emergencyPlan"
                  value={data.emergencyPlan || ''}
                  onChange={(e) => handleChange('emergencyPlan', e.target.value)}
                  placeholder="制定针对可能发生的紧急情况的应对措施..."
                  rows={4}
                />
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* 质量措施 */}
        <TabsContent value="quality" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <CheckCircle className="w-5 h-5 text-green-600" />
                质量控制措施
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div>
                <div className="flex justify-between items-center mb-2">
                  <Label>质量控制措施</Label>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => handleArrayAdd('qualityMeasures', '')}
                  >
                    <Plus className="w-4 h-4 mr-1" />
                    添加措施
                  </Button>
                </div>
                <div className="space-y-2">
                  {(data.qualityMeasures || []).map((measure, index) => (
                    <div key={index} className="flex gap-2">
                      <Textarea
                        value={measure}
                        onChange={(e) => handleArrayChange('qualityMeasures', index, e.target.value)}
                        placeholder="输入质量控制措施..."
                        rows={2}
                        className="flex-1"
                      />
                      <Button
                        variant="ghost"
                        size="icon"
                        onClick={() => handleArrayRemove('qualityMeasures', index)}
                      >
                        <Trash2 className="w-4 h-4 text-red-500" />
                      </Button>
                    </div>
                  ))}
                </div>
              </div>

              <div>
                <Label htmlFor="acceptanceCriteria">验收标准</Label>
                <Textarea
                  id="acceptanceCriteria"
                  value={data.acceptanceCriteria || ''}
                  onChange={(e) => handleChange('acceptanceCriteria', e.target.value)}
                  placeholder="说明工程完工后的验收标准和程序..."
                  rows={4}
                />
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* 环保措施 */}
        <TabsContent value="environmental" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Leaf className="w-5 h-5 text-green-600" />
                环境保护措施
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div>
                <div className="flex justify-between items-center mb-2">
                  <Label>环保措施清单</Label>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => handleArrayAdd('environmentalMeasures', '')}
                  >
                    <Plus className="w-4 h-4 mr-1" />
                    添加措施
                  </Button>
                </div>
                <div className="space-y-2">
                  {(data.environmentalMeasures || []).map((measure, index) => (
                    <div key={index} className="flex gap-2">
                      <Textarea
                        value={measure}
                        onChange={(e) => handleArrayChange('environmentalMeasures', index, e.target.value)}
                        placeholder="输入环保措施..."
                        rows={2}
                        className="flex-1"
                      />
                      <Button
                        variant="ghost"
                        size="icon"
                        onClick={() => handleArrayRemove('environmentalMeasures', index)}
                      >
                        <Trash2 className="w-4 h-4 text-red-500" />
                      </Button>
                    </div>
                  ))}
                </div>
              </div>

              <div>
                <Label htmlFor="environmentalImpact">环境影响评估</Label>
                <Textarea
                  id="environmentalImpact"
                  value={data.environmentalImpact || ''}
                  onChange={(e) => handleChange('environmentalImpact', e.target.value)}
                  placeholder="评估施工对环境的影响并提出相应对策..."
                  rows={4}
                />
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>

      {/* 编制依据 */}
      <div className="space-y-4">
        <h3 className="text-lg font-semibold text-gray-800">编制依据</h3>
        <div>
          <Label htmlFor="compilationBasis">编制依据</Label>
          <Textarea
            id="compilationBasis"
            value={data.compilationBasis || ''}
            onChange={(e) => handleChange('compilationBasis', e.target.value)}
            placeholder={`列出方案编制所依据的标准规范，例如：
GB 50060-2008 《3-110kV高压配电装置设计规范》
DL/T 5092-1999 《110-500kV架空送电线路设计技术规程》
GB 26859-2011 《电力安全工作规程 电力线路部分》`}
            rows={6}
          />
        </div>
      </div>
    </div>
  );
}
